const app = new Vue({
    el: '#app',
    data: {
        gameStarted: false,
        difficulty: 'normal',
        currentWord: {
            word: '',
            pinyin: [],
            explanation: ''
        },
        userInput: '',
        score: 0,
        timeLeft: 60,
        timer: null,
        dictionary: {},
        usedWords: new Set(),
        hintCount: 3,
        difficultySettings: {
            easy: { time: 90, hintCount: 5 },
            normal: { time: 60, hintCount: 3 },
            hard: { time: 30, hintCount: 1 }
        },
        sounds: {
            success: new Audio('sounds/success.mp3'),
            error: new Audio('sounds/error.mp3'),
            tick: new Audio('sounds/tick.mp3'),
            gameOver: new Audio('sounds/game-over.mp3'),
            newHighScore: new Audio('sounds/high-score.mp3'),
            hint: new Audio('sounds/hint.mp3'),
            start: new Audio('sounds/start.mp3')
        },
        showGameOver: false,
        isNewHighScore: false,
        tickSoundPlaying: false,
        showLeaderboard: false,
        leaderboard: [],
        playerName: '',
        combo: 0,  // 连击数
        maxCombo: 0,  // 最大连击数
        remainingTime: 0,  // 剩余时间奖励
        difficultyMultiplier: {
            easy: 1,
            normal: 1.5,
            hard: 2
        },
        achievements: {
            firstWin: false,
            comboMaster: false,
            speedMaster: false,
            timeMaster: false
        },
        showAchievement: false,
        achievementMessage: '',
    },
    computed: {
        timePercentage() {
            const settings = this.difficultySettings[this.difficulty];
            return (this.timeLeft / settings.time) * 100;
        },
        isTimeWarning() {
            const settings = this.difficultySettings[this.difficulty];
            return this.timeLeft <= settings.time * 0.3; // 剩余30%时间时显示警告
        },
        formattedTime() {
            const minutes = Math.floor(this.timeLeft / 60);
            const seconds = this.timeLeft % 60;
            return `${minutes}:${seconds.toString().padStart(2, '0')}`;
        },
        comboBonus() {
            return Math.floor(this.combo * 1.5);
        }
    },
    methods: {
        changeName() {
            const newName = prompt('请输入新的名字：');
            if (newName && newName.trim()) {
                this.playerName = newName.trim();
                localStorage.setItem('playerName', this.playerName);
            }
        },
        async startGame() {
            const settings = this.difficultySettings[this.difficulty];
            this.timeLeft = settings.time;
            this.hintCount = settings.hintCount;
            this.score = 0;
            this.usedWords.clear();
            this.showGameOver = false;
            this.isNewHighScore = false;
            this.combo = 0;
            this.maxCombo = 0;
            this.remainingTime = 0;
            
            if (Object.keys(this.dictionary).length === 0) {
                await this.loadDictionary();
            }
            
            if (!localStorage.getItem('playerName')) {
                const name = prompt('请输入您的名字：', '玩家' + Math.floor(Math.random() * 1000));
                if (name) {
                    localStorage.setItem('playerName', name);
                    this.playerName = name;
                }
            } else {
                this.playerName = localStorage.getItem('playerName');
            }
            
            this.playSound('start');
            this.gameStarted = true;
            this.setRandomWord();
            this.startTimer();
        },
        
        async loadDictionary() {
            try {
                const response = await fetch('data/idiom.json');
                const data = await response.json();
                data.forEach(item => {
                    const word = item.word.replace(/[，\s]/g, '');
                    this.dictionary[word] = {
                        word,
                        pinyin: item.pinyin.split(' '),
                        explanation: item.explanation
                    };
                });
            } catch (error) {
                console.error('加载成语词典失败:', error);
                alert('加载成语词典失败，请刷新页面重试');
            }
        },
        
        startTimer() {
            this.timer = setInterval(() => {
                this.timeLeft--;
                if (this.timeLeft <= 0) {
                    this.stopTickSound();
                    this.endGame();
                } else if (this.isTimeWarning) {
                    this.playTickSound();
                } else {
                    this.stopTickSound();
                }
            }, 1000);
        },
        
        endGame() {
            clearInterval(this.timer);
            this.stopTickSound();
            const highScore = localStorage.getItem('highScore') || 0;
            this.isNewHighScore = this.score > highScore;
            
            if (this.isNewHighScore) {
                localStorage.setItem('highScore', this.score);
                this.playSound('newHighScore');
            } else {
                this.playSound('gameOver');
            }
            
            // 更新排行榜
            this.updateLeaderboard();
            
            this.showGameOver = true;
        },
        
        restartGame() {
            // 保持当前难度重新开始
            this.showGameOver = false;
            this.startGame();
            this.playSound('start');
        },
        
        backToMenu() {
            this.showGameOver = false;
            this.gameStarted = false;
            this.score = 0;
            this.combo = 0;
            this.maxCombo = 0;
            this.userInput = '';
            this.usedWords.clear();
            this.stopTickSound();
        },
        
        setRandomWord() {
            const words = Object.values(this.dictionary);
            const randomIndex = Math.floor(Math.random() * words.length);
            const word = words[randomIndex];
            this.currentWord = word;
            this.usedWords.add(word.word);
        },
        
        checkAnswer() {
            const input = this.userInput.trim();
            const inputField = document.querySelector('input[type="text"]');
            
            if (!input) {
                this.showError('请输入成语', inputField);
                return;
            }
            
            if (!this.dictionary[input]) {
                this.showError('不是有效的成语', inputField);
                return;
            }
            
            if (this.usedWords.has(input)) {
                this.showError('该成语已经使用过了', inputField);
                return;
            }
            
            const lastChar = this.currentWord.word[this.currentWord.word.length - 1];
            const lastPinyin = this.currentWord.pinyin[this.currentWord.pinyin.length - 1];
            const firstPinyin = this.dictionary[input].pinyin[0];
            
            if (input[0] !== lastChar && !this.isPinyinEqual(firstPinyin, lastPinyin)) {
                this.showError('首尾字既不相同也不同音', inputField);
                this.combo = 0;  // 重置连击
                return;
            }
            
            // 答对了
            this.stopTickSound();
            this.combo++;  // 增加连击数
            this.maxCombo = Math.max(this.maxCombo, this.combo);
            
            // 检查成就
            this.checkAchievements();
            
            // 计算得分
            this.addScore();
            
            this.currentWord = this.dictionary[input];
            this.usedWords.add(input);
            this.userInput = '';
            
            // 添加成功效果
            inputField.classList.add('success-glow');
            setTimeout(() => inputField.classList.remove('success-glow'), 1000);
            
            this.playSound('success');
        },
        
        isPinyinEqual(pinyin1, pinyin2) {
            const normalize = (py) => py.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
            return normalize(pinyin1) === normalize(pinyin2);
        },
        
        addScore() {
            const baseScore = 100;
            const timeBonus = Math.round((this.timeLeft / this.difficultySettings[this.difficulty].time) * 50);
            const comboBonus = this.comboBonus;
            const difficultyBonus = this.difficultyMultiplier[this.difficulty];
            
            const totalScore = Math.round((baseScore + timeBonus + comboBonus) * difficultyBonus);
            this.score += totalScore;
            
            // 显示得分细节
            this.showScoreDetails(baseScore, timeBonus, comboBonus, difficultyBonus);
            
            // 重置时间
            this.timeLeft = this.difficultySettings[this.difficulty].time;
            this.remainingTime += this.timeLeft;
        },
        
        showScoreDetails(baseScore, timeBonus, comboBonus, difficultyBonus) {
            const details = document.createElement('div');
            details.className = 'score-popup';
            details.innerHTML = `
                <div class="score-detail">基础分：${baseScore}</div>
                <div class="score-detail">时间奖励：${timeBonus}</div>
                <div class="score-detail">连击奖励：${comboBonus}</div>
                <div class="score-detail">难度倍数：×${difficultyBonus}</div>
                <div class="total-score">总计：${Math.round((baseScore + timeBonus + comboBonus) * difficultyBonus)}</div>
            `;
            document.body.appendChild(details);
            setTimeout(() => details.remove(), 2000);
        },
        
        checkAchievements() {
            const achievements = [];
            
            // 首胜成就
            if (!this.achievements.firstWin && this.score >= 1000) {
                this.achievements.firstWin = true;
                achievements.push('初露锋芒：首次达到1000分！');
            }
            
            // 连击成就
            if (!this.achievements.comboMaster && this.combo >= 10) {
                this.achievements.comboMaster = true;
                achievements.push('连击大师：达成10连击！');
            }
            
            // 速度成就
            if (!this.achievements.speedMaster && this.timeLeft > this.difficultySettings[this.difficulty].time * 0.8) {
                this.achievements.speedMaster = true;
                achievements.push('神速：快速答题！');
            }
            
            // 时间大师成就
            if (!this.achievements.timeMaster && this.remainingTime >= 300) {
                this.achievements.timeMaster = true;
                achievements.push('时间大师：累计节省5分钟！');
            }
            
            // 显示成就
            if (achievements.length > 0) {
                this.showAchievementPopup(achievements);
                this.saveAchievements();
            }
        },
        
        showAchievementPopup(achievements) {
            this.achievementMessage = achievements.join('\n');
            this.showAchievement = true;
            setTimeout(() => {
                this.showAchievement = false;
            }, 3000);
        },
        
        saveAchievements() {
            localStorage.setItem('achievements', JSON.stringify(this.achievements));
        },
        
        loadAchievements() {
            const saved = localStorage.getItem('achievements');
            if (saved) {
                this.achievements = JSON.parse(saved);
            }
        },
        
        updateLeaderboard() {
            let leaderboard = JSON.parse(localStorage.getItem('leaderboard') || '[]');
            leaderboard.push({
                name: this.playerName,
                score: this.score,
                difficulty: this.difficulty,
                maxCombo: this.maxCombo,
                date: new Date().toLocaleDateString()
            });
            
            // 按分数排序并只保留前10名
            leaderboard.sort((a, b) => b.score - a.score);
            leaderboard = leaderboard.slice(0, 10);
            
            localStorage.setItem('leaderboard', JSON.stringify(leaderboard));
            this.leaderboard = leaderboard;
        },
        
        showLeaderboardModal() {
            this.leaderboard = JSON.parse(localStorage.getItem('leaderboard') || '[]');
            this.showLeaderboard = true;
        },
        
        getHint() {
            if (this.hintCount <= 0) {
                this.showError('提示次数已用完');
                return;
            }
            
            const lastChar = this.currentWord.word[this.currentWord.word.length - 1];
            const lastPinyin = this.currentWord.pinyin[this.currentWord.pinyin.length - 1];
            
            const possibleWords = Object.values(this.dictionary)
                .filter(word => {
                    const firstPinyin = word.pinyin[0];
                    return (word.word[0] === lastChar || this.isPinyinEqual(firstPinyin, lastPinyin)) && 
                           !this.usedWords.has(word.word);
                });
            
            if (possibleWords.length === 0) {
                this.showError('没有找到合适的提示成语');
                return;
            }
            
            const hint = possibleWords[Math.floor(Math.random() * possibleWords.length)];
            this.playSound('hint');
            alert(`提示：${hint.word}（${hint.explanation}）`);
            this.hintCount--;
        },
        
        showError(message, element = null) {
            if (element) {
                element.classList.add('error-shake');
                setTimeout(() => element.classList.remove('error-shake'), 500);
            }
            alert(message);
            this.playSound('error');
        },
        
        playTickSound() {
            if (!this.tickSoundPlaying) {
                this.tickSoundPlaying = true;
                this.sounds.tick.loop = true;
                this.sounds.tick.play().catch(e => console.log('音效播放失败:', e));
            }
        },
        
        stopTickSound() {
            if (this.tickSoundPlaying) {
                this.sounds.tick.pause();
                this.sounds.tick.currentTime = 0;
                this.tickSoundPlaying = false;
            }
        },
        
        playSound(type) {
            if (type === 'tick') {
                this.playTickSound();
                return;
            }
            
            try {
                // 停止倒计时音效
                if (type !== 'tick') {
                    this.stopTickSound();
                }
                // 重置音频
                this.sounds[type].currentTime = 0;
                // 播放音频
                this.sounds[type].play().catch(e => console.log('音效播放失败:', e));
            } catch (e) {
                console.log('音效播放失败:', e);
            }
        }
    },
    watch: {
        timeLeft(newValue) {
            if (this.isTimeWarning) {
                document.querySelector('.timer').classList.add('warning');
            } else {
                document.querySelector('.timer').classList.remove('warning');
            }
        }
    },
    beforeDestroy() {
        this.stopTickSound();
        Object.values(this.sounds).forEach(sound => {
            sound.pause();
            sound.currentTime = 0;
        });
    },
    created() {
        this.loadAchievements();
        if (localStorage.getItem('playerName')) {
            this.playerName = localStorage.getItem('playerName');
        }
    }
}); 